<?php
/**
 * Created by PhpStorm.
 * User: 24339
 * Date: 2018/10/29
 * Time: 9:32
 */

namespace app\index\controller;
use think\Db;
use think\Controller;
class Cases extends Controller
{
    public function lists(){
        $data = Db::table('case')->alias('c')->field('c.*,m.name')->join('company m',"m.id = c.cmpid")->select();
        $this->assign('data',$data);
        return view();
    }
    public function add(){
        $data = Db::table('company')->select();
        $this->assign('data',$data);
        if(request()->isPost()){
            $file = request()->file('caseimg');
            if($file){
                $info = $file->validate(['size'=>5242880,'ext'=>'jpg,png,gif'])->move(ROOT_PATH.'public/static/img');
                if($info){
                    $icon=str_replace("\\","/",$info->getSaveName());
                }
            }
//			dump(input('post.')n); //打印接收到的参数
            $data = [		//接受传递的参数
                'caseinfo' => input('caseinfo'),
                'cmpid' => input ('cmpid'),
                'caseimg' => $icon,
            ];
            $res = db('case')->insert($data);
            if($res){
                $this->success('添加案例成功','lists');
            }else{
                $this->error('添加案例失败');
            }
        }
        return view();
    }
    public function edit(){
        $data = Db::table('company')->select();
        $this->assign('data',$data);
        $id = input('id');
        $case = db('case')->find($id);
        $this->assign('case',$case);
        if(request()->isPost()){
            $place=input('oldplace');
            $file = request()->file("caseimg");
            if($file){
                $path = str_replace("\\","/",ROOT_PATH).'public/static/img/'.input('oldplace');//图片路径
                //var_dump($path);
                if (($place!=null||$place!='')&&file_exists($path)) {//判断图片路径是否存在
                    unlink($path);//删除旧图片
                }

                $info = $file->validate(['size'=>5242880,'ext'=>'jpg,png,gif'])->move(ROOT_PATH.'public/static/img');
                if($info){
                    $place=str_replace("\\","/",$info->getSaveName());
                }
            }
            $data = [		//接受传递的参数
                'caseinfo' => input('caseinfo'),
                'cmpid' => input ('cmpid'),
                'caseimg' => $place,
            ];
            $res = db('case')->where('id',input('id'))->update($data);
            if($res){
                $this->success('修改案例成功','lists');
            }else{
                $this->error('修改案例失败');
            }
        }
    return view();
    }
    public function del(){
        $id = input('id');
        $staff = db('case')->delete($id);
        if($staff){
            $this->success('删除成功','lists');
        }else{
            $this->error('删除失败');
        }
        return view();
    }
}